package com.zbkj.service.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zbkj.common.model.project.ProjectParamGuo;
import com.zbkj.common.model.project.ProjectParamJun;
import com.zbkj.service.dao.project.ProjectParamGuoMapper;
import com.zbkj.service.service.project.ProjectParamGuoService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 项目参数国标表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-10-07
 */
@Service
public class ProjectParamGuoServiceImpl extends ServiceImpl<ProjectParamGuoMapper, ProjectParamGuo> implements ProjectParamGuoService {

    @Override
    public ProjectParamGuo getParamGuo(Long projectId, Integer ptype) {
        if(Objects.isNull(projectId) || Objects.isNull(ptype)) {
            return null;
        }
        LambdaQueryWrapper<ProjectParamGuo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectParamGuo::getDeleteFlag,0)
                .eq(ProjectParamGuo::getProjectId,projectId)
                .eq(ProjectParamGuo::getPtype,ptype)
                .last(" limit 1");
        return this.getOne(wrapper,false);
    }

    @Override
    public List<ProjectParamGuo> getParamGuoList(Long projectId) {
        if(Objects.isNull(projectId)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<ProjectParamGuo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectParamGuo::getDeleteFlag,0)
                .eq(ProjectParamGuo::getProjectId,projectId);
        return this.list(wrapper);
    }

    @Override
    public ProjectParamGuo getParamGouByQueryType(int queryType, Long projectId) {
        if(Objects.isNull(projectId)) {
            return null;
        }
        if(queryType == 0) {
            return this.getParamGuo(projectId, 0);
        } else if(queryType == 1) {
            return this.getParamGuo(projectId, 1);
        } else {
            List<ProjectParamGuo> paramList = getParamGuoList(projectId);
            if(CollectionUtils.isEmpty(paramList)) {
                return null;
            }
            ProjectParamGuo param = paramList.stream().filter(v->v.getPtype() == 1).findFirst().orElse(null);
            return Objects.nonNull(param) ? param : paramList.stream().filter(v->v.getPtype() == 0).findFirst().orElse(null);
        }
    }

    @Override
    public boolean paramSaveFromAdmin(Long projectId, ProjectParamGuo paramGuo) {
        ProjectParamGuo paramGouDb = getParamGuo(projectId,1);
        paramGuo.setProjectId(projectId);
        paramGuo.setPtype(1);
        if(Objects.isNull(paramGouDb)) {
            return this.save(paramGuo);
        } else {
            paramGuo.setId(paramGouDb.getId());
            return this.updateById(paramGuo);
        }
    }

}
